package com.moyu.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.moyu.common.core.enums.ResultCode;
import com.moyu.common.security.exception.ServiceException;
import com.moyu.user.domain.permission.dto.PermissionQueryDTO;
import com.moyu.user.domain.role.Role;
import com.moyu.user.domain.role.dto.PermissionByRoleQueryDTO;
import com.moyu.user.domain.role.dto.RolePermissionSavaDTO;
import com.moyu.user.domain.role.vo.RoleListVO;
import com.moyu.user.domain.role.dto.RoleQueryDTO;
import com.moyu.user.domain.role.dto.RoleSaveDTO;
import com.moyu.user.mapper.RoleMapper;
import com.moyu.user.service.IRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * 角色服务实现类
 *
 * @Author 赵彦博
 * @Date 2025/3/25 18:30
 */
@Slf4j
@Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public List<RoleListVO> list(RoleQueryDTO roleQueryDTO) {
        PageHelper.startPage(roleQueryDTO.getPageNum(), roleQueryDTO.getPageSize());
        return roleMapper.selectRoleList(roleQueryDTO);
    }

    @Override
    public boolean deleteRole(Long roleId) {
        // 删除角色
        return roleMapper.deleteRoleById(roleId) > 0;
    }

    @Override
    public List<PermissionQueryDTO> getRolePermissionList(PermissionByRoleQueryDTO dto) {
        PageHelper.startPage(dto.getPageNum(),dto.getPageSize());
        return roleMapper.selectRolePermissionList(dto);
    }

    @Override
    public int addRole(RoleSaveDTO roleSaveDTO) {
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        Role role = roleMapper.selectOne(queryWrapper
                .eq(Role::getRoleName, roleSaveDTO.getRoleName()));
        // 检查角色名称是否已存在
        if (role != null) {
            throw new ServiceException(ResultCode.AILED_ROLE_EXISTS);
        }
        Role insertRole = new Role();
        insertRole.setRoleName(roleSaveDTO.getRoleName());
        // 插入角色信息
        return roleMapper.insert(insertRole);
    }

    @Override
    public int removeRolePermission(PermissionByRoleQueryDTO dto) {
        return roleMapper.removeRolePermission(dto);
    }

    @Override
    public List<PermissionQueryDTO> availablePermission(PermissionByRoleQueryDTO dto) {
        PageHelper.startPage(dto.getPageNum(),dto.getPageSize());
        return roleMapper.availablePermission(dto);
    }

    @Override
    public int addRolePermission(RolePermissionSavaDTO rolePermissionSavaDTO) {
        return roleMapper.addRolePermission(rolePermissionSavaDTO);
    }

}
